package bounceBall;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.util.Duration;

// 弹球类
public class BounceBall {
	private Circle ball;
	private Timeline timeline;
	private int dx = 1;
	private int dy = 1;
	
	public BounceBall(int centerX, int centerY, int radius, Color color) {
		ball = new Circle(centerX, centerY, radius, color);
		
		// 动画
		timeline = new Timeline(new KeyFrame(Duration.millis(8), e-> {
			moveBall(600, 400);
		}));
		timeline.setCycleCount(Timeline.INDEFINITE);
	}
	
	// 弹球的移动
	public void moveBall(double paneWidth, double paneHeight) {
		// 撞到墙
		if(ball.getCenterX()<ball.getRadius() || ball.getCenterX()>paneWidth - ball.getRadius()) {
			dx *= -1;
		}
		if(ball.getCenterY()<ball.getRadius() || ball.getCenterY()>paneHeight - ball.getRadius()) {
			dy *= -1; 
			
		}
		// 弹球相撞
		for(int i=0; i<Main.balls.size(); i++) {
			BounceBall temp = Main.balls.get(i);
			if(this != temp) {
				if(this.ball.getRadius() + temp.getBall().getRadius() + 2 >= computeDistance(temp.getBall())) {
					this.dx *= -1;
					this.dy *= -1;
					temp.setDx(temp.getDx() * -1);
					temp.setDy(temp.getDy() * -1);
				}
			}
		}
		ball.setCenterX(ball.getCenterX() + dx);
		ball.setCenterY(ball.getCenterY() + dy);
	}
	
	// 计算两弹球之间的距离
	public double computeDistance(Circle temp) {
		double distanceX = this.ball.getCenterX() - temp.getCenterX();
		double distanceY = this.ball.getCenterY() - temp.getCenterY();
		return Math.sqrt(distanceX*distanceX + distanceY*distanceY);
	}
	
	// 访问器与修改器
	public Circle getBall() {
		return ball;
	}

	public Timeline getTimeline() {
		return timeline;
	}
	
	public int getDx() {
		return dx;
	}
	
	public int getDy() {
		return dy;
	}
	
	public void setDx(int dx) {
		this.dx = dx;
	}
	
	public void setDy(int dy) {
		this.dy = dy;
	}
}
